#!/usr/bin/perl

use strict 'vars';
package main;

use Getopt::Std;
use Cwd;

use vars qw($opt_d $opt_p $opt_u);

#get command line options
getopts('d:u:p:');
if ($opt_d eq "" || $opt_p eq "") {
    die "Usage: start-i3-server.pl -d <conf_dir> -u <username> -p <path>\n";
}
if ($opt_u eq "") {
    $opt_u = "ucb_i3";
}

chdir ($opt_d) || die "Cannot change to conf directory\n";
opendir (CONF_DIR, ".") || die "Cannot open conf directory\n";

my $filename, my @arr, my $cmd;
while ($filename = readdir(CONF_DIR)) {
    if ($filename =~ "cfg") {
	@arr = split(/_/, $filename);
	print "Starting i3 on host $arr[1] at port $arr[2]\n";
	$cmd = "ssh $opt_u\@$arr[1] \"mkdir $opt_p\"";
	system($cmd);
	
	$cmd = "scp -C ../kill-process.pl ../i3_server2 $filename $opt_u\@$arr[1]:$opt_p";
	print "$cmd\n";
	system($cmd);
	
	$cmd = "ssh $opt_u\@$arr[1] \"cd $opt_p; ulimit -c 5000; nohup ./i3_server2 $filename $arr[2] 2>&1>/dev/null &\" &";
	print $cmd."\n";
	system($cmd);
	print "\n";
	sleep(15);
    }
}

close CONF_DIR;
